package geekstudy.week10;

/**
 *
 * 307. 区域和检索 - 数组可修改
 * https://leetcode-cn.com/problems/range-sum-query-mutable/
 *
 *
 * 执行结果：  通过  显示详情
 *
 * 添加备注
 * 执行用时：111 ms, 在所有 Java 提交中击败了42.46% 的用户
 * 内存消耗：68.4 MB, 在所有 Java 提交中击败了80.40% 的用户
 *
 *
 */
public class Week10RangeSumQueryMutable {

    int[] tree;
    int n;

    public Week10RangeSumQueryMutable(int[] nums) {
        if(nums.length > 0) {
            n = nums.length;
            tree = new int[n * 2];
            buildTree(nums);
        }
    }

    private void buildTree(int[] nums) {
        for(int right = n, left = 0; right < 2 * n; right++, left++) {
            tree[right] = nums[left];
        }
        for(int size = n - 1; size > 0; size--) {
            tree[size] = tree[size * 2] + tree[size * 2 + 1];
        }
    }

    public void update(int index, int val) {
        index += n;
        tree[index] = val;
        for(;index > 0;) {
            int left = index;
            int right = index;
            if(index % 2 == 0) {
                right = index + 1;
            } else {
                left = index - 1;
            }
            tree[index / 2] = tree[left] + tree[right];
            index /= 2;
        }
    }

    public int sumRange(int left, int right) {
        left += n;
        right += n;
        int sum = 0;
        for(;left <= right;) {
            if((left % 2) == 1) {
                sum += tree[left];
                left++;
            }
            if((right % 2) == 0 ) {
                sum += tree[right];
                right--;
            }
            left /= 2;
            right /= 2;
        }
        return sum;
    }
}
